package appfuse.framework;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import appfuse.framework.exceptions.BaseException;
import flex.messaging.io.SerializationContext;
import flex.messaging.io.amf.Amf3Input;
import flex.messaging.io.amf.Amf3Output;

/**
 * Flash AMF3类型专用Action
 * <p>
 * WebvegaFlashAction
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: Copyright (c) 2008
 * </p>
 * <p>
 * Company: appfuse
 * </p>
 * 
 * @author Felon
 * @since 2008-12-20
 */
abstract public class WebvegaFlashAction extends WebvegaBaseAction {
	Log log = LogFactory.getLog(this.getClass());

	private static final boolean NEED_ZIP = true;	//数据是否需要压缩
	
	Object m_inMap = new Object();
	
	public ActionForward executeAction(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws BaseException{
		
		response.setContentType("application/x-gzip-compressed");
		
		SerializationContext context = new SerializationContext();	//初始化序列
	    
		   
	    Amf3Output amf3Out = new Amf3Output(context);	//Amf3输入流	
	    Amf3Input amf3In = new Amf3Input(context);		//Amf3输入流
	
	    DeflaterOutputStream zipOutStream;	//解压缩输出流
	    InflaterInputStream zipInStream;	//压缩后的输入流
	    
		try {		
			
			//看是否需要压缩
			if(NEED_ZIP){			
				
				zipInStream = new InflaterInputStream(new DataInputStream(request.getInputStream()));
				zipOutStream = new DeflaterOutputStream(new DataOutputStream(response.getOutputStream()));
				amf3In.setInputStream(zipInStream);
				amf3Out.setOutputStream(zipOutStream);
			}else{
				amf3In.setInputStream(request.getInputStream());
				amf3Out.setOutputStream(response.getOutputStream());
			}
			
			
			m_inMap = amf3In.readObject();	
			
			Object outObject = doExecute(m_inMap,request,response);
			if(outObject != null){
				amf3Out.writeObject(outObject);
			}
			
			if(NEED_ZIP)			
				zipOutStream.finish();
			zipInStream.close();
			zipOutStream.close();			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	      
		return null;
	}
	
	
	abstract public Object doExecute(Object inMap,HttpServletRequest request, HttpServletResponse response);
}